// ActionScript file
import classes.AppConfig;

import com.dynamicflash.util.Base64;
import com.tinkerlog.WebCam;

import component.LoadingProgress;

import flash.display.Bitmap;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.TimerEvent;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.utils.Timer;

import mx.controls.Alert;
import mx.core.Application;
import mx.core.UIComponent;
import mx.graphics.codec.JPEGEncoder;
import mx.managers.PopUpManager;

import org.flexlancer.Logger.Logger;
import org.flexlancer.controller.Picture;
import org.flexlancer.events.PictureDoubleClickEvent;
			
			private var webCam:WebCam;
			[Bindable]
			private var picIndex:Number = 1;
			[Bindable]
			private var userName:String = "Guest";
			[Bindable]
			private var cMenu:ContextMenu;
			private var lpWaitForServer:LoadingProgress  = null ;
			public var LargPicture:Picture = null;
			private var cw:Number = 1920;
			private var ch:Number = 1080;
			private var tw:Number = 160;
			private var th:Number = 120;
			//private var ref:UIComponent = new UIComponent();

			private function init():void {
				try{
					//var pw:Number = Number(Application.application.parameters.cw);
					//var ph:Number = Number(Application.application.parameters.ch);
				    //Alert.show(pw.toString()+"x " +ph.toString());
				    this.initWebCam(cw,ch);
				     this.gallary.addEventListener(PictureDoubleClickEvent.PICTURE_DOUBLE_CLICK,OnPictureClicked);
				     this.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
				     this.cMenu = new ContextMenu();
					this.cMenu.addEventListener(ContextMenuEvent.MENU_SELECT,OnMenuSelect);
					
					AppConfig.LOGIN_USER = Application.application.parameters.currUser;
					//AppConfig.LOGIN_USER = "Khurram";
					if(AppConfig.LOGIN_USER){
						this.userName = AppConfig.LOGIN_USER;	
					}
				}catch(err:Error){
					Logger.LogE(err);
				}
		    }
			
			 private function initWebCam(w:Number, h:Number):void{
		    	try{
		    		this.myPreview.removeAllChildren();
			
				    webCam = new WebCam(w,h);
				     
 				    var ref:UIComponent = new UIComponent();
				    //ref.width = w;
				    //ref.height = h;
				    this.webCam.scaleX = this.webCam.scaleY = (this.panelContainer.width-20)/this.webCam.width;
					
				    this.myPreview.addChild(ref);
					ref.addChild(webCam);
					//setTimeout(this.setPanelToCenter,2000,this.webCam.height);
					this.setPanelToCenter(this.webCam.height);				    
				}catch(err:Error){
					Logger.LogE(err);
				}
		    }
			
			private function setPanelToCenter(pH:Number):void{
		    	//this.panelContainer.setStyle("verticalAlign","middle");
		    	//this.myPreview.setStyle("verticalCenter",0);
		    	var py:Number = (this.panelContainer.height - pH - 40)/2;
		    	this.myPreview.y = py;
		    }
			
			private function OnSizeChange():void{
		    	try{
		    		if ( this.cmbSize.selectedItem != null ){
						//this.myPreview.removeAllChildren();
						this.initWebCam(this.cmbSize.selectedItem.width,this.cmbSize.selectedItem.height);
		      		}
		    	}catch(err:Error){
		    		Logger.LogE(err);
		    	}
		    }

		    private function OnMenuSelect(evt:Event):void{
				try{
					var cItem:ContextMenuItem = new ContextMenuItem("DELETE IMAGE",true);
					cItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,OnDeleteSelected);
					this.cMenu.hideBuiltInItems();
					this.cMenu.customItems = new Array();
					this.cMenu.customItems.push(cItem);
				}catch(err:Error){
					Logger.LogE(err);
				}
			}

		    private function onKeyDown(evt:KeyboardEvent):void{
				try{
					if ( evt.keyCode == Keyboard.DELETE ){
						this.OnDeleteSelected();
					}	
				}catch(err:Error){
					Logger.LogE(err);
				}
			}
		   		  
		    private function takeSnapshot():void {
				try{
			        var photoData:Bitmap = this.webCam.getSnapshot();
			        photoData.width = tw;
			        photoData.height = th;
			        var insertPic:Picture = new Picture(photoData,this.txt_namingConvention.text + this.picIndex.toString());
			        insertPic.width = tw;
			        insertPic.height = th;
			        this.gallary.AddPicture(insertPic);
			        this.picIndex++;
				}catch(err:Error){
					Logger.LogE(err);
				}
		    }
		    
		    private function takeBurst():void {
		    	try{
		    		var timer:Timer = new Timer(1000,this.ns_burstValue.value-1);
		    		timer.addEventListener(TimerEvent.TIMER,this.TimerCalled);
		    		timer.start();
		    		this.takeSnapshot();
		    	}catch(err:Error){
		    		throw err;
		    	}
		    }
		    
		    private function TimerCalled(evt:TimerEvent):void{
		    	try{
		    		this.takeSnapshot();
		    	}catch(err:Error){
		    		Logger.LogE(err);
		    	}
		    }
			
			public function OnDeleteSelected(evt:Event = null):void{
				try{
					
					this.gallary.RemoveSelected();
				}catch(err:Error){
					Logger.LogE(err);
				}
			}

			private function uploadSnapshot(parmPicture:Picture):void {
				if ( this.lpWaitForServer == null ){
					this.lpWaitForServer = PopUpManager.createPopUp(this,LoadingProgress,true) as LoadingProgress;
					PopUpManager.centerPopUp(this.lpWaitForServer);
				}

				var uic:UIComponent = new UIComponent();
				uic.addChild(parmPicture.BitMap2);
				var bitmap:Bitmap = uic.getChildAt(0) as Bitmap;
				/*var img:Image = new Image();
				img.source = bitmap;
				img.height = this.cmbSize.selectedItem.height;
				img.width = this.cmbSize.selectedItem.width;
				this.addChild(img);
				var quality:Number = (this.cmbQuality.selectedItem.data) as Number;
				var jpgEncoder:JPEGEncoder = new JPEGEncoder(quality);
				var jpgBytes:ByteArray = jpgEncoder.encode(ImageSnapshot.captureBitmapData(img));
				uploadPhoto(jpgBytes,parmPicture);
				*/
				var quality:Number = (this.cmbQuality.selectedItem.data) as Number;
		          
				var jpgEncoder:JPEGEncoder = new JPEGEncoder(quality);
				var jpgBytes:ByteArray = jpgEncoder.encode(bitmap.bitmapData);        
				uploadPhoto(jpgBytes,parmPicture);
		          
				//this.removeChild(img);
			}
			
			private function uploadPhoto(imageData:ByteArray,parmPicture:Picture):void {
				//var request:URLRequest = new URLRequest("http://localhost:50336/upload.aspx");
				var request:URLRequest = new URLRequest(Application.application.parameters.saveurl);
				var vars:URLVariables = new URLVariables();
				vars.name = parmPicture.Name;
				//vars.comment = commentField.text;
        
				vars.bindata = Base64.encodeByteArray(imageData);
				request.method = "POST";       
				var loader:URLLoader = new URLLoader();               
				loader.addEventListener(Event.COMPLETE, uploadPhotoHandler);
				request.data = vars;
				loader.load(request);        
			}
      private function uploadPhotoHandler(event:Event):void {
      	//Alert.show(event.target.data,"Image uploaded");
      	this.upload_count --;
      	if ( this.upload_count == 0 ){
      		PopUpManager.removePopUp(this.lpWaitForServer);
      		this.lpWaitForServer = null;
      	}else{
      		this.uploadSnapshot(this.gallary.Collection[this.upload_count - 1]);
      	}
      }
			
			//==========================================================
			private var upload_count:Number = 0;
			private function OnSaveAll():void{
				try{
					this.upload_count = this.gallary.Collection.length;
					
					/*for each ( var singleImage:Picture in this.gallary.Collection ){
						this.uploadSnapshot(singleImage);
					}*/
					if ( this.upload_count > 0 )
						this.uploadSnapshot(this.gallary.Collection[this.upload_count - 1]);
				}catch(err:Error){
					Logger.LogE(err);
				}
			}
			
			private function OnSaveClick():void{
				try{
					if ( this.chkAll.selected ){
						this.OnSaveAll();						
					}else{
						if ( this.gallary.Selected != null ){
							this.uploadSnapshot(this.gallary.Selected);
							this.upload_count = 1;
						}
					}
				}catch(err:Error){
					Logger.LogE(err);
				}
			}
			
			public function OnNameChange(evt:Event):void{
				try{
					if(txt_namingConvention.text.length < 1){
						Alert.show("There should be a name","Naming Convention"); 
					}
				}catch(err:Error){
					Logger.LogE(err);
				}
			}
			
			public function OnNumChange(evt:Event):void{
				try{
					if(txt_startingnumber.text.length < 1){
						Alert.show("There should be a number","Naming Convention"); 
					}else{
						this.picIndex = Number(txt_startingnumber.text);
					}
				}catch(err:Error){
					Logger.LogE(err);
				}
			}
						
			public function OnPictureClicked(evt:PictureDoubleClickEvent):void {
				try {
					this.LargPicture= evt.selected_picture;
					
					var LargeImage:ShowLargImage = PopUpManager.createPopUp(this,ShowLargImage,true) as ShowLargImage;
					LargeImage.caller=this;
					LargeImage.displayImage.source = this.LargPicture.BitMap;
					PopUpManager.centerPopUp(LargeImage);
				}catch(err:Error){
					Logger.LogE(err);
				}
			} 
			 /* Button to reload complete Application 
		   private function OnReloadClick():void{
		    	try{
		    		var urlRequest:URLRequest = new URLRequest(Application.application.url);
					navigateToURL(urlRequest,"_self");
					}
		    	}catch(err:Error){
		    		Logger.LogE(err);
		    	}
		    } */